const express = require('express');
const router = express.Router();
const { Course, User, Chapter, Category } = require('../models');
const { successResponse, failureResponse } = require('../utils/responses')
const { NotFoundError } = require('../utils/errors')

// 查询章节详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params
    // const condition = {
    //   attributes: { exclude: ['CourseId'] },
    //   include: [
    //     {
    //       model: Course,
    //       as: 'course',
    //       attributes: ['id', 'name'],
    //       include: [{
    //         model: User,
    //         as: 'user',
    //         attributes: ['id', 'username', 'nickname', 'avatar', 'company']
    //       },]
    //     }
    //   ]
    // }
    const chapter = await Chapter.findByPk(id, { attributes: { exclude: ['CourseId'] } });
    if (!chapter) throw new NotFoundError(`ID: ${id} 的课程详情不存在`);

    const course = await chapter.getCourse({ attributes: ['id', 'name', 'userId'] });

    const user = await course.getUser({ attributes: ['id', 'username', 'nickname', 'avatar', 'company'] });
    // 查询同一课程的所有章节
    const chapters = await Chapter.findAll({
      attributes: { exclude: ['CourseId', 'content'] },
      where: { CourseId: chapter.courseId },
      order: [['rank', 'asc'], ['id', 'desc']],
    });

    successResponse(res, '成功查询课程详情', { chapter, chapters, course, user });
  } catch (error) {
    failureResponse(res, error);
  }
});

module.exports = router;